package org.rency.spring.cloud.boot.mvc.customer;

import org.rency.spring.cloud.boot.mvc.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * ${todo}
 *
 * @author: Created by user_rcy@163.com on 2016/8/19.
 * @version: V1.0.0
 * @since JDK 1.8
 */
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MemberService memberService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置不拦截规则
        web.ignoring().antMatchers("/static/**", "/**/*.jsp");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/welcome").permitAll();
        http.authorizeRequests().antMatchers("/error").permitAll();
        http.authorizeRequests().antMatchers("/csrf").permitAll();
        http.authorizeRequests().anyRequest().authenticated();

        http.authorizeRequests().and().formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password")
                .successForwardUrl("/loginSuccess")
                .failureUrl("/login?error")
                .permitAll();
        http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).deleteCookies("remember-me");
        http.rememberMe();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(memberService);//.passwordEncoder(new ShaPasswordEncoder());
    }

}
